package org.sanguine.tests.tenderpro.sax;

import com.sun.org.apache.xml.internal.utils.DefaultErrorHandler;
import org.xml.sax.*;
import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Author: Alexey Kuznetsov
 * Date: 19.02.14
 * SVN $Id$
 */
public class SaxXMLWorker {
    private final static String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
    private final static String W3C_XML_SCHEMA = XMLConstants.W3C_XML_SCHEMA_NS_URI;

    private SAXParserFactory spf = SAXParserFactory.newInstance();
    private SAXParser saxParser;
    private XMLReader xmlReader;

    public SaxXMLWorker(ContentHandler handler, boolean xsd) throws ParserConfigurationException, SAXException {
        spf.setNamespaceAware(true);
        spf.setValidating(true);
        saxParser = spf.newSAXParser();
        if (xsd) {
            saxParser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
        }
        xmlReader = saxParser.getXMLReader();
        if (handler != null) xmlReader.setContentHandler(handler);
        xmlReader.setErrorHandler(new DefaultErrorHandler(true));
    }

    public void parse(String fileURI) throws IOException, SAXException {
        if (xmlReader != null && fileURI != null && !fileURI.isEmpty()) xmlReader.parse(fileURI);
    }
}
